//
//  CSearchView.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-19.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CSearchView.h"

//===============================================================================================

@implementation CSearchBar

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (@selector(paste:) == action)
    {
        NSLog(@"paste");
        return NO;
    }
    
    return NO;
}

@end

//===============================================================================================

@implementation CSearchView

@synthesize delegate;
@synthesize m_SearchBar;
//@synthesize m_SearchCondition;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        delegate = nil;
        
        [self InitSearchView];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
//search
-(void)InitSearchView
{
    m_SearchBar = [[CSearchBar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    m_SearchBar.backgroundColor=[UIColor clearColor];
    m_SearchBar.delegate = self;
    m_SearchBar.placeholder = @"条件之间用空格隔开";
    m_SearchBar.keyboardType = UIKeyboardTypeDefault;
    [[m_SearchBar.subviews objectAtIndex:0]removeFromSuperview];
    for (UIView *subview in m_SearchBar.subviews) 
    {  
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {  
            [subview removeFromSuperview];  
            break;  
        }  
    }
    view.backgroundColor = self.backgroundColor;
    [m_SearchBar insertSubview:view atIndex:0];
    [view release];
    [self addSubview:m_SearchBar];
    [m_SearchBar release];
}

-(void)dealloc
{
    [super dealloc];
}

-(void)AddSearchConditionView:(CSearchConditionView*)view
{    
    /*m_SearchCondition = view;
    [m_SearchCondition retain];
    m_SearchCondition.m_Delegate = self;
    [m_SearchCondition HiddenSearchConditionView];*/
}

-(void)DidSearchConditionViewSelected:(int)index Text:(NSString *)text
{
    //[m_SearchCondition HiddenSearchConditionView];
    
    //[delegate DidSearchViewSelected:index Text:m_SearchBar.text];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //[m_SearchCondition ShowSearchConditionView];
    [delegate DidSearchViewEdited];

    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    //[m_SearchCondition HiddenSearchConditionView];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //[m_SearchCondition HiddenSearchConditionView];
    
    [searchBar resignFirstResponder];
    
    //[delegate DidSearchViewSelected:m_SearchCondition.m_nIndex Text:m_SearchBar.text];
    NSString *str = nil;
    NSString *new = nil;
    if ([m_SearchBar.text length] > 0)
    {
        str = [m_SearchBar.text stringByReplacingOccurrencesOfString:@" " withString:@","];
        NSRange range = {[str length]-1, 1};
        if ([[str substringWithRange:range] isEqualToString:@","])
        {
            range.location = 0;
            range.length   = str.length-1;
            new = [NSString stringWithString:[str substringWithRange:range]];
        }
        else 
        {
            new = [NSString stringWithString:str];
        }
    }
    
    NSLog(@"%@(length:%d)", new, [new length]);
    m_SearchBar.text = new;
    [delegate DidSearchViewSelected:-2 Text:m_SearchBar.text];
}
/*
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchBar.text length] > 0)
    {
        NSRange range   = {[searchBar.text length]-1, 1};
        NSString *value = [searchBar.text substringWithRange:range];
        NSString *set   = nil;
        
        if ([value isEqualToString:@","] || [value isEqualToString:@"，"])
        {
            range.length   = [searchBar.text length]-1;
            range.location = 0;
            set = [NSString stringWithString:[searchBar.text substringWithRange:range]];
            searchBar.text = set;
        }
        //space
        else if ([value isEqualToString:@" "])
        {
            ;
        }
        //Special characters
        else if (![self CheckIuput:value Range:NSMakeRange(-1, -1)])
        {
            range.length   = [searchBar.text length]-1;
            range.location = 0;
            set = [NSString stringWithString:[searchBar.text substringWithRange:range]];
            searchBar.text = set;
        }
    }
}
*/
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //NSLog(@"searchText:%@", searchText);
    if ([searchText length] > 0)
    {
        
        NSRange range = {[searchText length]-1, 1};
        if (![self CheckIuput:[searchText substringWithRange:range] Range:range])
        {
            range.location = 0;
            range.length   = [searchText length] - 1;
            m_SearchBar.text = [searchText substringWithRange:range];
        }
    }
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
    //NSLog(@"%@", text);
    return [self CheckIuput:text Range:range];
}

-(BOOL)CheckIuput:(NSString*)value Range:(NSRange)range
{
    //commit search
    if ([value isEqualToString:@"\n"])
    {
        return YES;
    }
    //delete
    else if (1 == range.length && 0 == [value length])
    {
        return YES;
    }
    else if (0 == range.location)
    {
        if ([value isEqualToString:@" "] || [value isEqualToString:@","] || [value isEqualToString:@"，"] || ![self CheckSpecialCharacters:value])
        {
            return NO;
        }
    }
    else if ([value isEqualToString:@","] || [value isEqualToString:@"，"])
    {
        return NO;
    }
    else if ([value isEqualToString:@" "])
    {
        if (range.location > 0)
        {
            NSRange rang = {range.location-1, 1};
            if ([value isEqualToString:[m_SearchBar.text substringWithRange:rang]])
            {
                return NO;
            }
        }
        
        return YES;
    }
    //special characters
    else if (![self CheckSpecialCharacters:value])
    {
        return NO;
    }
    
    return YES;
}

-(BOOL)CheckSpecialCharacters:(NSString*)value
{
    NSString *emailRegex = @"[A-Za-z0-9]+$"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    if(![emailTest evaluateWithObject:value])
    {
        if ([self CheckChineseCharacters:value] || [value length] > 1)
        {
            return YES;
        }
        else 
        {
            return NO;
        }
    }
    
    return YES;
}

-(BOOL)CheckChineseCharacters:(NSString*)value
{
    NSString *emailRegex = @"[\u4e00-\u9fa5]"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:value];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    //[m_SearchCondition HiddenSearchConditionView];
    
    [searchBar resignFirstResponder];
    
    [delegate DidSearchViewSelected:-1 Text:nil];
}

@end
